import { watchOnce } from '@peng_kai/kit/libs/vueuse';
import { useHandshakeQuery } from '~/modules/query-client/queries';
import { getResourcePath, joinPath } from '~/utils';

export const useAppStore = defineStore('app', () => {
  // #region 握手协议相关
  const { handshakeQry, handshake, appName, isAgent } = useHandshakeQuery();

  /** 拼接 CDN 路径 */
  const joinCdnPath = (...paths: Array<string | undefined | null>) => {
    const cdn = handshake.value?.domain.cdn;
    const _paths = paths.filter(Boolean) as string[];
    return (cdn && _paths.length) ? joinPath(cdn, ..._paths) : '';
  };

  /** 获取 CDN 资源路径 */
  const getCdnResPath = (...args: Parameters<typeof getResourcePath>) => {
    const cdn = handshake.value?.domain.cdn;
    const path = getResourcePath(...args);
    return (cdn && path) ? joinPath(cdn, path) : '';
  };
  // #endregion

  const hiddenBalanceReason = ref('');

  watch(appName, (appName) => {
    if (!appName)
      return;

    const ogTitleEl = document.querySelector(`meta[property="og:title"]`) as HTMLMetaElement;
    document.title = ogTitleEl.content = appName;
  });

  watchOnce(handshakeQry.status, (v) => {
    if (v === 'success') {
      window.posId = handshake.value?.promotion_channel?.pos_id;
      window.posPlatform = handshake.value?.promotion_channel?.platform;
    }
  });

  return {
    handshakeQry,
    handshake,
    appName,
    isAgent,
    joinCdnPath,
    getCdnResPath,
    hiddenBalanceReason,
  };
});
